package com.scedu.utils;

import com.mysql.cj.log.Log;
import com.scedu.config.JWTConfig;
import com.scedu.exception.CommonException;
import com.scedu.result.ResultCode;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

@Getter
@Setter
@Component
@Slf4j
public class JwtUtils {
    @Autowired
    JWTConfig jwtConfig;

    /*
    设置认证token
    id:登录用户id
    subject 登录用户名username
    Map<String,Object> 其他信息
     */
    public  String createJwt(String id, String subject, Map<String,Object> map){



        jwtConfig.setSecret_key(Base64.encode(jwtConfig.getKey().getBytes()));
        //0.获取当前时间 毫秒
        long now=System.currentTimeMillis();
        //1.设置失效时间
        long exp=now+jwtConfig.getTtl();
        //2.生成jwtBuilder
        JwtBuilder jwtBuilder= Jwts.builder()
                .setId(id) //用户id
                .setSubject(subject) //登录用户名
                .setIssuedAt(new Date()) //签名时间
                .setExpiration(new Date(exp)) //失效时间
                .signWith(SignatureAlgorithm.HS256,jwtConfig.getSecret_key());//利用秘钥加密生成token
        //3.根据map生成claims
        //jwtBuilder.setClaims(map);
        Set<Map.Entry<String,Object>> entries=map.entrySet();//entrySet()方式
        Iterator<Map.Entry<String,Object>> iteratorentries=entries.iterator();
        while(iteratorentries.hasNext()){
            Map.Entry<String,Object> entry=iteratorentries.next();
            jwtBuilder.claim(entry.getKey(),entry.getValue());
        }
        //4.创建token
        String token = jwtBuilder.compact();
        return  token;

    }
    /*
    解析token字符串获取clamis
     */
    public  Claims parseJwt(String token) throws Exception{
        Claims claims = null;
       jwtConfig.setSecret_key(Base64.encode(jwtConfig.getKey().getBytes()));
        try {
            claims = Jwts.parser().setSigningKey(jwtConfig.getSecret_key()).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            //new Throwable(e);
            throw new CommonException(ResultCode.JWT_HEADER_ERROR);
        }
        return claims;
    }
}
